package com.shuwen.gcdj.service.basics;


import com.alibaba.excel.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shuwen.gcdj.bean.DictResp;
import com.shuwen.gcdj.bean.basicsEquitment.request.*;
import com.shuwen.gcdj.bean.basicsEquitment.response.*;
import com.shuwen.gcdj.bean.sysDictionary.request.SysDictionaryReq;
import com.shuwen.gcdj.bean.sysDictionary.response.SysDictionaryResp;
import com.shuwen.gcdj.common.api.CommonPage;
import com.shuwen.gcdj.common.api.CommonResult;
import com.shuwen.gcdj.common.constant.Constants;
import com.shuwen.gcdj.common.constant.MemberCst;
import com.shuwen.gcdj.common.exception.ApiException;
import com.shuwen.gcdj.common.util.BeanHelper;
import com.shuwen.gcdj.common.util.IOCloseUtil;
import com.shuwen.gcdj.dto.account.InitUserDto;
import com.shuwen.gcdj.entity.Account;
import com.shuwen.gcdj.entity.Department;
import com.shuwen.gcdj.entity.SysDictionary;
import com.shuwen.gcdj.entity.basics.*;
import com.shuwen.gcdj.mapper.mysql.AccountMapper;
import com.shuwen.gcdj.mapper.mysql.DepartmentMapper;
import com.shuwen.gcdj.mapper.mysql.basics.*;
import com.shuwen.gcdj.mapper.mysql.sysDictionary.SysDictionaryMapper;
import com.shuwen.gcdj.service.file.ExcelService;
import com.shuwen.gcdj.service.file.FilePackaging;
import com.shuwen.gcdj.service.sysDictionary.SysDictionaryService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import sun.util.calendar.LocalGregorianCalendar;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Service
@Slf4j
@AllArgsConstructor
public class EquipmentService extends MethodFactory {

    private final BasicsEquipmentMapper basicsEquipmentMapper;
    private final BasicsEquipmentparameterMapper basicsEquipmentparameterMapper;
    private final BasicsSmallcarparameterMapper basicsSmallcarparameterMapper;
    private final BasicsBelowcarparameterMapper basicsBelowcarparameterMapper;
    private final BasicsMaintenancecraneMapper basicsMaintenancecraneMapper;
    private final BasicsResourceMapper basicsResourceMapper;
    private final BasicsResourceService basicsResourceService;
    private final SysDictionaryMapper sysDictionaryMapper;
    private final SysDictionaryService sysDictionaryService;
    private final ExcelService excelService;
    private final AccountMapper accountMapper;
    private final DepartmentMapper departmentMapper;
    private static String uploadId;

    public static String getUploadId() {
        return uploadId;
    }

    public static void setUploadId(String uploadId) {
        EquipmentService.uploadId = uploadId;
    }

    public CommonResult<EquipmentTitleResp> getEquipmentTitle(String code) {
        SysDictionaryReq sysDictionaryReq = new SysDictionaryReq();
        sysDictionaryReq.setParentCode(code);
        List<String> titles = sysDictionaryMapper.getList(sysDictionaryReq).stream().map(SysDictionaryResp::getName).collect(Collectors.toList());
        EquipmentTitleResp equipmentTitleResp = new EquipmentTitleResp();
        SysDictionary sysDictionary = sysDictionaryMapper.selectOne(new QueryWrapper<SysDictionary>()
                .lambda().eq(SysDictionary::getCode, code));
        equipmentTitleResp.setIsShowParameter(sysDictionary.getValue().equals(Constants.ONE));
        equipmentTitleResp.setEquipmentTitleUp(titles.get(Constants.ZERO));
        equipmentTitleResp.setEquipmentTitleBelow(titles.get(Constants.ONE));
        return CommonResult.success(equipmentTitleResp);
    }

    public CommonResult<List<EquipmentTypeResp>> getEquipmentTypeList() {
        SysDictionaryReq sysDictionaryReq = new SysDictionaryReq();
        sysDictionaryReq.setParentCode(Constants.EQUIPMENT_TYPE_CONFIG);
        List<EquipmentTypeResp> equipmentTypeRespList = sysDictionaryMapper.getList(sysDictionaryReq).stream().map(temp -> {
            EquipmentTypeResp data = new EquipmentTypeResp();
            data.setEquipmentTypeName(temp.getName());
            data.setEquipmentTypeCode(temp.getCode());
            return data;
        }).collect(Collectors.toList());
        return CommonResult.success(equipmentTypeRespList);
    }

    /**
     * 台账增加
     */
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<StandingbookResp> equipmentAdd(StandingbookReq req, InitUserDto initUserDto) {
        List<BasicsEquipment> basicsEquipments = basicsEquipmentMapper.selectList(new QueryWrapper<BasicsEquipment>().lambda()
                .eq(BasicsEquipment::getCode, req.getEquipmentReq().getCode()));
        if (!CollectionUtils.isEmpty(basicsEquipments)) {
            return CommonResult.failed("该数据已存在");
        }
        //优先添加设备主表
        BasicsEquipment basicsEquipment = new BasicsEquipment();
        BeanUtils.copyProperties(req.getEquipmentReq(), basicsEquipment);
        basicsEquipment.setCreateId(initUserDto.getUserId());
        basicsEquipment.setUpdateId(initUserDto.getUserId());
        basicsEquipmentMapper.insert(basicsEquipment);
        //添加设备基本参数
        BasicsEquipmentparameter basicsEquipmentparameter = new BasicsEquipmentparameter();
        BeanUtils.copyProperties(req.getEquipmentparameterReq(), basicsEquipmentparameter);
        basicsEquipmentparameter.setEquipmentId(basicsEquipment.getId());
        basicsEquipmentparameter.setCreateId(initUserDto.getUserId());
        basicsEquipmentparameter.setUpdateId(initUserDto.getUserId());
        basicsEquipmentparameter.setCreateTime(LocalDateTime.now());
        basicsEquipmentparameter.setUpdateTime(LocalDateTime.now());
        basicsEquipmentparameterMapper.insert(basicsEquipmentparameter);
        //添加上小车
        BasicsSmallcarparameter basicsSmallcarparameter = new BasicsSmallcarparameter();
        BeanUtils.copyProperties(req.getSmallcarparameterReq(), basicsSmallcarparameter);
        basicsSmallcarparameter.setEquipmentId(basicsEquipment.getId());
        basicsSmallcarparameter.setCreateId(initUserDto.getUserId());
        basicsSmallcarparameter.setUpdateId(initUserDto.getUserId());
        basicsSmallcarparameterMapper.insert(basicsSmallcarparameter);
        //添加下小车
        BasicsBelowcarparameter basicsBelowcarparameter = new BasicsBelowcarparameter();
        BeanUtils.copyProperties(req.getBelowcarparameterReq(), basicsBelowcarparameter);
        basicsBelowcarparameter.setEquipmentId(basicsEquipment.getId());
        basicsBelowcarparameter.setCreateId(initUserDto.getUserId());
        basicsBelowcarparameter.setUpdateId(initUserDto.getUserId());
        basicsBelowcarparameter.setCreateTime(LocalDateTime.now());
        basicsBelowcarparameter.setUpdateTime(LocalDateTime.now());
        basicsBelowcarparameterMapper.insert(basicsBelowcarparameter);
        //添加维修调
        BasicsMaintenancecrane basicsMaintenancecrane = new BasicsMaintenancecrane();
        BeanUtils.copyProperties(req.getMaintenancecraneReq(), basicsMaintenancecrane);
        basicsMaintenancecrane.setEquipmentId(basicsEquipment.getId());
        basicsMaintenancecrane.setCreateId(initUserDto.getUserId());
        basicsMaintenancecrane.setUpdateId(initUserDto.getUserId());
        basicsMaintenancecraneMapper.insert(basicsMaintenancecrane);
        StandingbookResp standingbookResp = new StandingbookResp();
        standingbookResp.setId(basicsEquipment.getId());
        return CommonResult.success(standingbookResp);
    }

    /**
     * 台账修改
     */
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> equipmentUpdate(EquipmentDetailsReq req, InitUserDto initUserDto) {
        List<BasicsEquipment> basicsEquipments = basicsEquipmentMapper.selectList(new QueryWrapper<BasicsEquipment>().lambda()
                .eq(BasicsEquipment::getId, req.getEquipmentReq().getId()));
        Account account = accountMapper.selectById(req.getEquipmentReq().getManager());
        if (account.getIsDelete().equals(Constants.IS_DELETE_YES)) {
            return CommonResult.failed("该人员被删除");
        }
        if (CollectionUtils.isEmpty(basicsEquipments)) {
            return CommonResult.failed("该数据不存在");
        }
        //修改设备主表
        BasicsEquipment basicsEquipment = new BasicsEquipment();
        BeanUtils.copyProperties(req.getEquipmentReq(), basicsEquipment);
        basicsEquipment.setUpdateId(initUserDto.getUserId());
        basicsEquipmentMapper.updateById(basicsEquipment);
        //修改设备基本参数
        BasicsEquipmentparameter basicsEquipmentparameter = new BasicsEquipmentparameter();
        BeanUtils.copyProperties(req.getEquipmentparameterReq(), basicsEquipmentparameter);
        basicsEquipmentparameter.setUpdateId(initUserDto.getUserId());
        basicsEquipmentparameterMapper.updateById(basicsEquipmentparameter);
        //修改上小车
        BasicsSmallcarparameter basicsSmallcarparameter = new BasicsSmallcarparameter();
        BeanUtils.copyProperties(req.getSmallcarparameterReq(), basicsSmallcarparameter);
        basicsSmallcarparameter.setUpdateId(initUserDto.getUserId());
        basicsSmallcarparameterMapper.updateById(basicsSmallcarparameter);
        //修改下小车
        BasicsBelowcarparameter basicsBelowcarparameter = new BasicsBelowcarparameter();
        BeanUtils.copyProperties(req.getBelowcarparameterReq(), basicsBelowcarparameter);
        basicsBelowcarparameter.setUpdateId(initUserDto.getUserId());
        basicsBelowcarparameterMapper.updateById(basicsBelowcarparameter);
        //修改维修调
        BasicsMaintenancecrane basicsMaintenancecrane = new BasicsMaintenancecrane();
        BeanUtils.copyProperties(req.getMaintenancecraneReq(), basicsMaintenancecrane);
        basicsMaintenancecrane.setUpdateId(initUserDto.getUserId());
        basicsMaintenancecraneMapper.updateById(basicsMaintenancecrane);
        return CommonResult.success("修改成功");
    }

    /**
     * 台账列表
     */
    public CommonResult<CommonPage<EquipmentListResp>> equipmentList(ListPageReq req) {
        Page<EquipmentListResp> page = new Page<>(req.getPageNum(), req.getPageSize(), true);
        IPage<EquipmentListResp> list = basicsEquipmentMapper.getList(page, req);
        List<EquipmentListResp> res = list.getRecords();
        Page<EquipmentListResp> resPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        resPage.setRecords(res);
        return CommonResult.success(CommonPage.restPage(resPage));
    }

    /**
     * 批量删除台账
     */
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> deleteEquioments(String ids, InitUserDto initUserDto) {
        String[] split = ids.split(",");
        for (String s : split) {
            basicsEquipmentMapper.update(null, new UpdateWrapper<BasicsEquipment>().lambda()
                    .eq(BasicsEquipment::getId, s)
                    .set(BasicsEquipment::getUpdateId, initUserDto.getUserId())
                    .set(BasicsEquipment::getIsDelete, Constants.IS_DELETE_YES));
        }
        return CommonResult.success("删除成功");
    }

    /**
     * 获取设备区域
     */
    public CommonResult<List<DictResp>> getEquipmentType() {
        return this.getType(Constants.EQUIPMENT_TYPE);
    }


    /**
     * 获取设备类型
     */
    public CommonResult<List<DictResp>> getEquipmentAreas() {
        return this.getType(Constants.AREAS);
    }

    /**
     * 获取安装区域
     */
    public CommonResult<List<DictResp>> getInstallAreas() {
        return this.getType(Constants.INSTALL_AREAS);
    }

    /**
     * 获取安装区域
     */
    public CommonResult<String> getFolderId(String id) {
        EquipmentService.setUploadId(id);
        return CommonResult.success("成功");
    }


    /**
     * 获取设备对象
     */
    public CommonResult<List<DictResp>> getEquipment() {
        List<BasicsEquipment> basicsEquipments = basicsEquipmentMapper.selectList(new QueryWrapper<BasicsEquipment>()
                .lambda().eq(BasicsEquipment::getIsDelete, Constants.IS_DELETE_NORMAL));
        List<DictResp> dictResps = BeanHelper.copyList(basicsEquipments, DictResp.class);
        return CommonResult.success(dictResps);
    }

    /**
     * 获取设备管理员
     */
    public CommonResult<List<DictResp>> getEquipmentAdmin() {
        List<Account> accounts = accountMapper.selectList(new QueryWrapper<Account>().lambda()
                .eq(Account::getIsDelete, Constants.IS_DELETE_NORMAL));
        List<DictResp> dictRes = new ArrayList<>();
        for (Account account : accounts) {
            DictResp dictResp = new DictResp();
            dictResp.setName(account.getShowName());
            dictResp.setValue(account.getId());
            dictResp.setState(account.getIsActive());
            dictRes.add(dictResp);
        }

        return CommonResult.success(dictRes);
    }


    /**
     * 获取部门
     */
    public CommonResult<List<DictResp>> getDept() {
        List<Department> departments = departmentMapper.selectList(new QueryWrapper<Department>().lambda()
                .eq(Department::getIsDelete, Constants.IS_DELETE_NORMAL));
        List<DictResp> dictResps = new ArrayList<>();
        for (Department department : departments) {
            DictResp dictResp = new DictResp();
            dictResp.setName(department.getName());
            dictResp.setValue(department.getId());
            dictResps.add(dictResp);
        }

        return CommonResult.success(dictResps);
    }

    /**
     * 设备台账详情
     */
    public CommonResult<EquipmentDetailsResp> getEquipmentDetails(String id) {
        BasicsEquipment basicsEquipment = basicsEquipmentMapper.selectById(id);
        BasicsEquipmentparameter basicsEquipmentparameter = basicsEquipmentparameterMapper.selectOne(
                new QueryWrapper<BasicsEquipmentparameter>()
                        .lambda()
                        .eq(BasicsEquipmentparameter::getIsDelete, Constants.IS_DELETE_NORMAL)
                        .eq(BasicsEquipmentparameter::getEquipmentId, id));
        BasicsSmallcarparameter basicsSmallcarparameter = basicsSmallcarparameterMapper.selectOne(
                new QueryWrapper<BasicsSmallcarparameter>()
                        .lambda()
                        .eq(BasicsSmallcarparameter::getIsDelete, Constants.IS_DELETE_NORMAL)
                        .eq(BasicsSmallcarparameter::getEquipmentId, id));
        BasicsBelowcarparameter basicsBelowcarparameter = basicsBelowcarparameterMapper.selectOne(
                new QueryWrapper<BasicsBelowcarparameter>()
                        .lambda()
                        .eq(BasicsBelowcarparameter::getIsDelete, Constants.IS_DELETE_NORMAL)
                        .eq(BasicsBelowcarparameter::getEquipmentId, id));
        BasicsMaintenancecrane basicsMaintenancecrane = basicsMaintenancecraneMapper.selectOne(
                new QueryWrapper<BasicsMaintenancecrane>()
                        .lambda()
                        .eq(BasicsMaintenancecrane::getIsDelete, Constants.IS_DELETE_NORMAL)
                        .eq(BasicsMaintenancecrane::getEquipmentId, id));

        EquipmentDetailsResp equipmentDetailsResp = new EquipmentDetailsResp();
        Belowcarparameter belowcarParameter = new Belowcarparameter();
        Equipmentparameter equipmentParameter = new Equipmentparameter();
        EquipmentResp equipment = new EquipmentResp();
        Maintenancecrane maintenancecrane = new Maintenancecrane();
        Smallcarparameter smallcarparameter = new Smallcarparameter();

        BeanUtils.copyProperties(basicsEquipment, equipment);
        BeanUtils.copyProperties(basicsEquipmentparameter, equipmentParameter);
        BeanUtils.copyProperties(basicsSmallcarparameter, smallcarparameter);
        BeanUtils.copyProperties(basicsBelowcarparameter, belowcarParameter);
        BeanUtils.copyProperties(basicsMaintenancecrane, maintenancecrane);

        equipmentDetailsResp.setEquipmentReq(equipment);
        equipmentDetailsResp.setEquipmentparameterReq(equipmentParameter);
        equipmentDetailsResp.setBelowcarparameterReq(belowcarParameter);
        equipmentDetailsResp.setMaintenancecraneReq(maintenancecrane);
        equipmentDetailsResp.setSmallcarparameterReq(smallcarparameter);
        return CommonResult.success(equipmentDetailsResp);
    }


    /**
     * 进入设备绑定设计资料（头部路径）
     */
    public CommonResult<List<FolderPreviewResp>> getFilePath(String id) {
        BasicsEquipment basicsEquipment = basicsEquipmentMapper.selectById(id);
        List<BasicsResource> basicsResources = basicsResourceMapper.selectList(new QueryWrapper<BasicsResource>().lambda()
                .eq(BasicsResource::getIsDelete, Constants.IS_DELETE_NORMAL)
                .eq(BasicsResource::getId, basicsEquipment.getResourceId()));
        List<FolderPreviewResp> folderPreviewResps = BeanHelper.copyList(basicsResources, FolderPreviewResp.class);
        return CommonResult.success(folderPreviewResps);
    }

    /**
     * 文件上传
     */
    public CommonResult<String> uploadFile(MultipartFile file) {
        String allPath = this.getPathNamed();
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        if (StringUtils.isEmpty(originalFilename)) {
            return CommonResult.failed("文件有误");
        }
        BasicsResource basicsResource = new BasicsResource();
        //判断名文件是否存在
        List<BasicsResource> basicsResources = basicsResourceMapper.selectList(
                new QueryWrapper<BasicsResource>().lambda()
                        .eq(BasicsResource::getIsDelete, Constants.IS_DELETE_NORMAL)
                        .eq(BasicsResource::getName, originalFilename));
        if (!CollectionUtils.isEmpty(basicsResources)) {
            Calendar instance = Calendar.getInstance();
            originalFilename = originalFilename.substring(0, originalFilename.indexOf(".")) + "-" + instance.getTimeInMillis() + suffix;

        }

        basicsResource.setName(originalFilename);
        basicsResource.setPath(Constants.IS_HIDDEN_ALL);
        basicsResource.setIsFolder(false);
        basicsResource.setEquipmentId(Constants.IS_HIDDEN_ALL);
        basicsResource.setDepth(Constants.IS_TEMP);
        basicsResource.setState(Constants.IS_TEMP);
        basicsResource.setSize(BigDecimal.valueOf(file.getSize()));
        basicsResource.setSuffix(suffix);
        basicsResource.setType(Constants.MENU_TYPE);
        basicsResource.setStoragePath(Constants.IS_HIDDEN_ALL);
        String path = excelService.uploadFile(file, true, allPath);
        basicsResource.setPath(path);
        basicsResourceMapper.insert(basicsResource);
        return CommonResult.success(basicsResource.getId());
    }

    /**
     * 报修-文件上传
     */
    public CommonResult<String> uploadFileFlow(MultipartFile file) {
        String path = excelService.uploadFile(file, false, "");
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isEmpty(originalFilename)) {
            return CommonResult.failed("文件有误");
        }
        BasicsResource basicsResource = new BasicsResource();
        basicsResource.setName(file.getOriginalFilename());
        basicsResource.setPath(path);
        basicsResource.setIsFolder(false);
        basicsResource.setEquipmentId(Constants.IS_HIDDEN_ALL);
        basicsResource.setDepth(Constants.IS_FLOW);
        basicsResource.setState(Constants.IS_TEMP);
        basicsResource.setSize(BigDecimal.valueOf(file.getSize()));
        basicsResource.setSuffix(originalFilename.substring(originalFilename.lastIndexOf(".")));
        basicsResource.setType(Constants.MENU_TYPE);
        basicsResource.setStoragePath(Constants.IS_HIDDEN_ALL);
        basicsResourceMapper.insert(basicsResource);
        return CommonResult.success(basicsResource.getId());
    }


    /**
     * 文件绑定父级
     */
    public CommonResult<String> addFile(FolderBangReq req) {
        BasicsResource basicsResource = basicsResourceMapper.selectById(req.getId());
        BasicsResource parentResource = basicsResourceMapper.selectById(req.getParentId());

        if (!StringUtils.isEmpty(req.getParentId()) || !StringUtils.isEmpty(parentResource)) {
            basicsResource.setStoragePath(req.getParentId());
            basicsResource.setDepth(parentResource.getDepth() + 1);
        } else {
            basicsResource.setStoragePath(Constants.IS_HIDDEN_ALL);
        }
        basicsResourceMapper.updateById(basicsResource);
        return CommonResult.success("绑定成功");
    }

    /**
     * 设计资料-下载
     */
    public void fileDetails(String id, HttpServletResponse response) {
        BasicsResource basicsResource = basicsResourceMapper.selectById(id);
        if (StringUtils.isEmpty(basicsResource)) {
            throw new ApiException("数据不存在");
        }
        if (basicsResource.getIsFolder().equals(true)) {
            String name = this.getPathNamed() + "/" + basicsResource.getName();
            toZip(name, basicsResource, response);
        } else {
            FilePackaging.download(response, basicsResource.getPath());
        }
    }

    public void toZip(String sourceFileName, BasicsResource basicsResource, HttpServletResponse response)
            throws RuntimeException {
        ZipOutputStream out = null;
        BufferedOutputStream bos = null;
        try {
            //将zip以流的形式输出到前台
            response.setHeader("content-type", "application/zip");
            response.setCharacterEncoding("utf-8");
            // 设置浏览器响应头对应的Content-disposition
            response.setHeader("Content-disposition",
                    "attachment;filename=" + new String("ocn".getBytes("gbk"), "iso8859-1") + ".zip");
            //创建zip输出流
            out = new ZipOutputStream(response.getOutputStream());
            //创建缓冲输出流
            bos = new BufferedOutputStream(out);
            String name = sourceFileName.split("/")[sourceFileName.split("/").length - 1];
            //调用压缩函数
            compress(out, bos, basicsResource, name + "/");
            out.flush();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOCloseUtil.close(bos, out);
        }
    }

    /**
     * 递归寻找目录
     *
     * @param out
     * @param bos
     * @param basicsResource
     * @param name
     */
    public void compress(ZipOutputStream out, BufferedOutputStream bos, BasicsResource basicsResource, String name) {
        FileInputStream fos = null;
        BufferedInputStream bis = null;
        String pathName = name;
        List<BasicsResource> basicsResources = basicsResourceMapper.selectList(
                new QueryWrapper<BasicsResource>().lambda()
                        .eq(BasicsResource::getIsDelete, Constants.IS_DELETE_NORMAL)
                        .eq(BasicsResource::getStoragePath, basicsResource.getId()));

        if (!CollectionUtils.isEmpty(basicsResources)) {
            try {
                for (BasicsResource basics : basicsResources) {
                    if (basics.getIsFolder()) {
                        out.putNextEntry(new ZipEntry(pathName + basics.getName() + "/"));
                        name = name + basics.getName() + "/";
                        compress(out, bos, basics, name);

                    } else {
                        out.putNextEntry(new ZipEntry(pathName + basics.getName()));
                        fos = new FileInputStream(basics.getPath());
                        bis = new BufferedInputStream(fos);

                        int tag;
                        //将源文件写入到zip文件中
                        while ((tag = bis.read()) != -1) {
                            out.write(tag);
                        }
                        bis.close();
                        fos.close();
                    }
                }
            } catch (Exception e) {
                log.info(e.getMessage());
            } finally {
                IOCloseUtil.close(bis, fos);
            }
        }


    }

    /**
     * 设计资料-新增文件夹
     */
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> addFile(FolderAddReq req) {
        int depthing = 0;
        BasicsResource basicsed = basicsResourceMapper.selectById(req.getId());
        if (!StringUtils.isEmpty(basicsed)) {
            depthing = basicsed.getDepth() + 1;
        }
        List<BasicsResource> basicsResources = basicsResourceMapper.selectList(new QueryWrapper<BasicsResource>().lambda()
                .eq(BasicsResource::getName, req.getName())
                .eq(BasicsResource::getIsDelete, Constants.IS_DELETE_NORMAL)
                .eq(BasicsResource::getDepth, depthing));
        if (!CollectionUtils.isEmpty(basicsResources)) {
            return CommonResult.failed("文件已存在");
        }
        BasicsResource basicsResource = new BasicsResource();
        if (StringUtils.isEmpty(req.getId())) {
            basicsResource.setStoragePath(Constants.IS_HIDDEN_ALL);
        } else {
            basicsResource.setStoragePath(req.getId());
        }
        basicsResource.setName(req.getName());
        basicsResource.setPath(Constants.IS_HIDDEN_ALL);
        basicsResource.setEquipmentId(Constants.IS_HIDDEN_ALL);
        if (StringUtils.isEmpty(req.getId())) {
            basicsResource.setDepth(Constants.IS_HIDDEN_NORMAL);
        } else {
            BasicsResource basics = basicsResourceMapper.selectById(req.getId());
            Integer depth = basics.getDepth();
            depth = depth + 1;
            basicsResource.setDepth(depth);
        }
        basicsResource.setIsFolder(true);
        basicsResource.setState(Constants.IS_HIDDEN_NORMAL);
        basicsResource.setSize(BigDecimal.valueOf(0.00));
        basicsResource.setSuffix(Constants.IS_HIDDEN_ALL);
        basicsResource.setType(Constants.IS_HIDDEN_NORMAL);
        basicsResourceMapper.insert(basicsResource);
        return CommonResult.success(basicsResource.getId());
    }

    /**
     * 设计资料-设备路径
     */
    public CommonResult<List<Object>> selectFile(SelectDetailReq req) {
        BasicsResource basicsResource = basicsResourceMapper.selectById(req.getId());
        if(basicsResource==null){
            basicsResource=new BasicsResource();
        }
        FileDictResp fileDictResp = new FileDictResp();
        BeanUtils.copyProperties(basicsResource, fileDictResp);
        List<Object> objects = new ArrayList<>();
        objects.add(basicsResource);
        List<Object> folder = this.getFolder(fileDictResp, objects);
        return CommonResult.success(folder);
    }

    /**
     * 设计资料-重命名
     */
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> restFile(FolderUpdate req) {
        BasicsResource basicsResource = basicsResourceMapper.selectById(req.getFileId());
        basicsResource.setUpdateTime(null);
        List<BasicsResource> basicsResources = basicsResourceMapper.selectList(new QueryWrapper<BasicsResource>()
                .lambda()
                .eq(BasicsResource::getIsDelete, Constants.IS_DELETE_NORMAL)
                .eq(BasicsResource::getId, req.getFileId()));
        if (CollectionUtils.isEmpty(basicsResources)) {
            return CommonResult.failed("文件不存在");
        }
        List<BasicsResource> basicsName = basicsResourceMapper.selectList(new QueryWrapper<BasicsResource>()
                .lambda()
                .eq(BasicsResource::getIsDelete, Constants.IS_DELETE_NORMAL)
                .eq(BasicsResource::getStoragePath,basicsResource.getStoragePath())
                .eq(BasicsResource::getName, req.getName()));
        if (!CollectionUtils.isEmpty(basicsName)) {
            return CommonResult.failed("文件名重复");
        }
        basicsResource.setName(req.getName());
        basicsResourceMapper.update(basicsResource, new UpdateWrapper<BasicsResource>().lambda()
                .eq(BasicsResource::getId, req.getFileId()));
        return CommonResult.success("修改成功");
    }

    /**
     * 设计资料-移动
     */
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> moveFile(MoveFileReq req) {
        BasicsResource nowResource = basicsResourceMapper.selectById(req.getId());
        BasicsResource targetResource = basicsResourceMapper.selectById(req.getTargetId());
        if (StringUtils.isEmpty(nowResource)) {
            return CommonResult.failed("数据不存在");
        }
        if (StringUtils.isEmpty(req.getTargetId())) {
            nowResource.setStoragePath(Constants.IS_HIDDEN_ALL);
            nowResource.setDepth(Constants.IS_HIDDEN_NORMAL);
        } else {
            nowResource.setStoragePath(req.getTargetId());
            nowResource.setDepth(targetResource.getDepth() + 1);
        }
        if (!StringUtils.isEmpty(targetResource) && targetResource.getIsFolder().equals(false)) {
            throw new ApiException("目标对象只能是文件夹");
        }
        MethodFactory.setFlag(true);
        Boolean path = this.getPath(new ArrayList<>(), req.getId(), req.getTargetId());
        nowResource.setUpdateTime(null);
        if (path) {
            return CommonResult.failed("不能移动到自己或子文件夹下");
        }
        basicsResourceMapper.updateById(nowResource);
        return CommonResult.success("移动完成");
    }

    /**
     * 设计资料-删除
     */
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> deleteFile(String ids) {
        String[] split = ids.split(",");
        for (String id : split) {
            BasicsResource basicsResource = basicsResourceMapper.selectById(id);
            List<BasicsEquipment> basicsEquipments = basicsEquipmentMapper.selectList(new QueryWrapper<BasicsEquipment>()
                    .lambda().eq(BasicsEquipment::getResourceId, id));
            if (!CollectionUtils.isEmpty(basicsEquipments)) {
                throw new ApiException("该文件夹或子文件夹被绑定,请换绑后在删除");
            }
            if (StringUtils.isEmpty(basicsResource)) {
                throw new ApiException("数据不存在");
            }
            basicsResource.setIsDelete(Constants.IS_DELETE_YES);
            basicsResource.setUpdateId(MemberCst.LOGIN_USER_ID);
            basicsResource.setUpdateTime(null);
            basicsResourceMapper.updateById(basicsResource);
            List<String> folderId = this.getFolderId(new ArrayList<>(), id);
            for (String sid : folderId) {
                List<BasicsEquipment> basicsFolder = basicsEquipmentMapper.selectList(new QueryWrapper<BasicsEquipment>()
                        .lambda().eq(BasicsEquipment::getResourceId, sid));
                if (!CollectionUtils.isEmpty(basicsFolder)) {
                    throw new ApiException("该文件夹或子文件夹被绑定,请换绑后在删除");
                }
                BasicsResource basics = basicsResourceMapper.selectById(sid);
                if (StringUtils.isEmpty(basics)) {
                    throw new ApiException("数据不存在");
                }
                basics.setIsDelete(Constants.IS_DELETE_YES);
                basics.setUpdateId(MemberCst.LOGIN_USER_ID);
                basics.setUpdateTime(null);
                basicsResourceMapper.updateById(basics);
            }
        }
        return CommonResult.success("删除成功");
    }


    /**
     * 根据文件夹id获取所有的子集
     *
     * @param ids
     * @param id
     * @return
     */
    public List<String> getFolderId(List<String> ids, String id) {
        List<BasicsResource> basicsResources = basicsResourceMapper.selectList(
                new QueryWrapper<BasicsResource>().lambda()
                        .eq(BasicsResource::getStoragePath, id)
                        .eq(BasicsResource::getIsDelete, Constants.IS_DELETE_NORMAL));
        if (!CollectionUtils.isEmpty(basicsResources)) {
            for (BasicsResource basicsResource : basicsResources) {
                ids.add(basicsResource.getId());
                if (basicsResource.getIsFolder()) {
                    getFolderId(ids, basicsResource.getId());
                }
            }
        }
        return ids;
    }

    /**
     * 设计资料-预览
     */
    public void filePreview(String id, HttpServletResponse response) {
        BasicsResource basicsResource = basicsResourceMapper.selectById(id);
        FilePackaging.download(response, basicsResource.getPath());
    }

    /**
     * 设计资料-获取所有文件夹
     */
    public CommonResult<List<FileDictResp>> getFiles() {
        List<BasicsResource> basicsResources = basicsResourceMapper.selectList(
                new QueryWrapper<BasicsResource>().lambda()
                        .eq(BasicsResource::getIsFolder, Constants.ADD_TYPE_NORMAL_ADD)
                        .eq(BasicsResource::getIsDelete, Constants.IS_DELETE_NORMAL)
                        .orderByDesc(BasicsResource::getCreateTime));
        List<FileDictResp> fileDictResps = BeanHelper.copyList(basicsResources, FileDictResp.class);
        return CommonResult.success(fileDictResps);
    }

    /**
     * 设计资料-文件夹树结构
     */
    public CommonResult<List<FileDictResp>> fileChilds(FolderIdReq req) {
        List<FileDictResp> list = basicsResourceMapper.getList(req.getId());
        List<FileDictResp> flow = this.getShu(list);
        return CommonResult.success(flow);
    }

    /**
     * 获取设计资料
     */
    public CommonResult<CommonPage<FileDictResp>> getFileDetails(FolderListReq req) {
        Page<FileDictResp> page = new Page<>(req.getPageNum(), req.getPageSize(), true);
        IPage<FileDictResp> all = basicsResourceMapper.getAll(page, req, req.getId());
        List<FileDictResp> records = all.getRecords();
        List<FileDictResp> flow = this.getFlow(records, req);
        Page<FileDictResp> resPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        resPage.setRecords(flow);
        return CommonResult.success(CommonPage.restPage(resPage));
    }

    /**
     * 获取设备对象
     *
     * @param req 设备类型、设备区域
     * @return
     */
    public List<EquipmentObjectResp> getEquipmentObject(EquipmentObjectReq req) {
        return basicsEquipmentMapper.getEquipmentObject(req);
    }

    /**
     * 获取设备对象
     *
     * @param
     * @return
     */
    public EquipmentStatisticsResp getEquipmentStatistics(String equipmentId) {
        EquipmentStatisticsResp equipmentStatisticsResp = new EquipmentStatisticsResp();
        //获取设备数量
        List<BasicsEquipment> equipmentList = basicsEquipmentMapper.selectList(new LambdaQueryWrapper<BasicsEquipment>()
                .eq(BasicsEquipment::getIsDelete, 0)
        );
        if (!CollectionUtils.isEmpty(equipmentList)) {
            //设备总数
            equipmentStatisticsResp.setEquipmentTotal(equipmentList.size());
            BasicsEquipment model = equipmentList.stream().filter(x -> x.getId().equals(equipmentId)).findFirst().orElse(null);

            EquipmentDetailsResp detail = getEquipmentDetails(model.getId()).getData();
            //获取设备详情
            if (detail != null) {
                equipmentStatisticsResp.setEquipmentName(detail.getEquipmentReq().getName());
                equipmentStatisticsResp.setEquipmentCode(detail.getEquipmentReq().getCode());
                equipmentStatisticsResp.setRatedLoad(detail.getEquipmentparameterReq().getCraneLoadMax());
                equipmentStatisticsResp.setHeight(detail.getEquipmentparameterReq().getBeamBottomHeight());
                equipmentStatisticsResp.setSpanBaseDistance(detail.getEquipmentparameterReq().getSpanBaseDistance());
                //获取传感器数量配置
                List<SysDictionaryResp> sensors = sysDictionaryService.getChildByParentCode("SensorInformationStatistics");
                if (!CollectionUtils.isEmpty(sensors)) {
                    SysDictionaryResp sensor = sensors.stream().filter(set->set.getOperateObject().equals(detail.getEquipmentReq().getCode())).findFirst().orElse(null);
                    equipmentStatisticsResp.setSensorTotal(sensor!=null ? Integer.parseInt(sensor.getCode()) : 0);
                    equipmentStatisticsResp.setMonitoringPoint(sensor != null ? Integer.parseInt(sensor.getName()) : 0);
                }
            }
        }
        return equipmentStatisticsResp;
    }
}
